package com.cooper.android.comm;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import android.content.res.AssetManager;
import android.util.Log;

public class FileUtils {

	public static String extractExtName(File file) {
		if (file.getName().contains(".")) {
			return file.getName().substring(file.getName().lastIndexOf("."));
		}
		return "";	
	}

	public static String extractNoExtFileName(File file) {	
		if (file.getName().contains(".")) {
			return file.getName().substring(0, file.getName().lastIndexOf("."));
		}
		return file.getName();			
	}
	
	public static String extractNoExtFilePath(File file) {
		if (file.getName().contains(".")) {
			return file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("."));
		}
		return file.getAbsolutePath();				
	}

	public static void delete(File dirOrFile) {

		if (dirOrFile == null || !dirOrFile.exists())
			return;
		if (dirOrFile.isDirectory()) {
			for (File file : dirOrFile.listFiles()) {
				if (file.isFile())
					file.delete();
				else if (file.isDirectory())
					delete(file);
			}
		}
		dirOrFile.delete();
	}

	public static String stringToFileName(String url) {

		String result = url.replace("http://", "c").replaceAll(
				"[\\s\\.\\\\/:\\(\\)@#&$\\-\\[\\]%\'`^!*\"<>|]", "_");
		if (url.length() >= 256) {
			return result.substring(0, 255);
		} else
			return result;
	}

	public static String readTextFile(String path) throws IOException {
		StringBuffer result = new StringBuffer();

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				new FileInputStream(path)));
		try {
			String line = reader.readLine();
			while (line != null) {
				result.append(line);
				result.append("\n");
				line = reader.readLine();
			}
		} finally {
			reader.close();
		}
		return result.toString();
	}

	public static void writerTextFile(String path, String text)
			throws IOException {
		FileWriter out = new FileWriter(path);
		try {
			out.write(text);
			out.flush();
		} finally {
			out.close();
		}
	}

	public static void copyAssetsFile(AssetManager asset, String src,
			String target) {
		try {
			InputStream in = asset.open(src);
			try {
				if (in != null) {
					File outFile = new File(target);
					if (outFile.exists()) {
						outFile.delete();
					}
					OutputStream out = new FileOutputStream(outFile);
					try {
						byte[] buf = new byte[1024];
						int len;
						while ((len = in.read(buf)) > 0) {
							out.write(buf, 0, len);
						}
					} finally {
						out.close();
					}
				}
			} finally {
				in.close();
			}

		} catch (Exception e) {
			Log.d("FileUtils", e.getMessage(), e);
		}
	}
}
